export const loadFile = function (name) { // name为文件所在位置
	let xhr = new XMLHttpRequest(),
		okStatus = document.location.protocol === "file:" ? 0 : 200;
	xhr.open('GET', name, false);
	xhr.overrideMimeType("text/html;charset=utf-8"); //默认为utf-8
	xhr.send(null);
	return xhr.status === okStatus ? xhr.responseText : null;
}

export const parse = (fileName) => {
	const fileStr = loadFile(fileName);
	if (fileStr.indexOf("We're sorry but default doesn't work properly without JavaScript enabled. Please enable it to continue.") !== -1) {
		alert("读取失败");
		return;
	}
	const snsArr = fileStr.split(/[(\r\n)\r\n]+/);
	const P = {
		points: [],
		lines: []
	};
	snsArr.forEach((item, index) => {
		if (!item) {
			return;
		}
		if (!index) {
			//第一行解析 名称
		} else if (index === 1) {
			//第二行解析 参数名
			const params = [];
			let param = undefined;
			for (let t of item) {
				if (t === '"') {
					if (param === undefined) {
						param = '';
					} else {
						params.push({
							name: param
						});
						param = undefined;
					}
				} else {
					if (param !== undefined) {
						// 获取参数
						param += t;
					}
				}
			}
			P['params'] = params;
		} else if (index === 2) {
			//第三行解析
			let param = '';
			let key = '';
			let value = '';
			for (let t of item) {
				if (key !== '') {
					if (value !== '' && (t === ' ' || t === ',')) {
						// 保存
						P[key] = value;
						key = '';
						value = '';
					} else if (t !== ' ' && t !== ',' && t !== '"') {
						value += t;
					}
				} else if (t === '=') {
					key = param;
					param = '';
				} else if (t !== ' ' && t !== ',' && t !== '"') {
					param += t;
				} else {
					param = '';
				}
			}
			if (key !== '') {
				P[key] = value;
			}
		} else if (index < Number(P.n) + 3) {
			let params = item.split(' ');
			params = params.filter(item => item !== '');
			params = params.map(item => Number(item));
			params.forEach((item, i) => {
				const {
					min,
					max
				} = P['params'][i];
				if ((!min && min !== 0) || (!max && max !== 0)) {
					P['params'][i] = {
						...P['params'][i],
						min: item,
						max: item
					}
				} else {
					P['params'][i] = {
						...P['params'][i],
						min: min > item ? item : min,
						max: max < item ? item : max,
					}
				}
			})
			P.points.push(params);
		} else {
			let params = item.split(' ');
			params = params.filter(item => item !== '');
			params = params.map(item => Number(item));
			P.lines.push(params);
		}
	});
	const x = P.params[0].max;
	const y = P.params[1].max;
	const z = P.params[2].max;
	P.lookup = {
		x: 0,
		y: 0,
		z: z
	};
	console.log(x, y, z)
	return P;
}
